#include "stdinc.h"

#include "../File.h"

CFile* CFile::Open(char* fname, s32 flags)
{
	FILE *f;
	if (flags & FILE_WRITE)
		f = fopen(fname, "wb");
	else
		f = fopen(fname, "rb");

	if (!f)
		return NULL;

	CFile *file = new CFile();
	file->m_file = f;

	if (flags & FILE_READ)
	{
		fseek(f, 0, SEEK_END);
		file->m_size = ftell(f);
		fseek(f, 0, SEEK_SET);
	}
	else
	{
		file->m_size = 0;
	}

	file->m_pos = 0;
	return file;
}

CFile::CFile()
{

}

CFile::~CFile()
{
	Close();
}

s32 CFile::Read(void* ptr, s32 count)
{
	fread(ptr, count, 1, m_file);
	s32 pos = ftell(m_file);
	s32 dif = pos - m_pos;
	m_pos = pos;
	return dif;
}

s32 CFile::Write(void* ptr, s32 count)
{
	fwrite(ptr, count, 1, m_file);
	s32 pos = ftell(m_file);
	s32 dif = pos - m_pos;
	m_pos = pos;
	return dif;
}

void CFile::Flush()
{
	fflush(m_file);
}


void CFile::Close()
{
	if (m_file)
	{
		fclose(m_file);
		m_file = NULL;
	}
}